<template>
    <div id="subPage">
        <div class="left">
            <div class="input">
                <Input search enter-button placeholder="请输入关键字" v-show="inputShow" v-model="keyword" clearable/>
                <Input v-show="inputShow" search  placeholder="请输入关键字" style="opacity:0;position: absolute;top:-9999px;width:1px;" clearable/>
            </div>
            <div class="scorll">
                <el-tree ref="treeBox" :data="treeData" :render-content="renderContent" :filter-node-method="filterNode" :expand-on-click-node="false" :highlight-current="true" :default-expanded-keys="expandedKeys" :current-node-key="currentKey" :props="defaultProps" @node-click="getTreeId"  node-key="issueTypeId"></el-tree>
            </div>
            <div class="btn" v-if="auth.isType">
                <div class="button cancel" @click="updateRow(5)">类别管理</div>
            </div>
        </div>
        <div class="right" >
            <div class="top">
                <div class="operationBox" style="margin-bottom:0.15rem;" v-if="auth.isAdd">
                    <div class="tableBtn" v-if="!detailAddFlag"  @click="updateRow(6)">
                        <div class="btnBox">
                            <div class="text">+  添加明细</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bottom">
                <div class="tableBox">
                    <div class="tableList">
                        <el-table :data="issueList" style="width: 100%" height="100%" :stripe="true">
                            <template slot="empty">
                                <div class="no_lsit" style="width:96%;margin:auto;">
                                    <img src="./../../assets/images/common/rotary_nodata.png" alt=""
                                        style="width:3.9rem; height: 2.4rem;">
                                </div>
                            </template>
                            <el-table-column prop="content" label="检查内容">
                                <template slot-scope="scope">
                                    <Tooltip  transfer :content="scope.row.content" placement="top-start"  max-width='200'>
                                        <p style="width:200px;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;cursor: pointer;">
                                            {{scope.row.content}}
                                        </p>
                                    </Tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column prop="require" label="整改要求">
                                <template slot-scope="scope">
                                    <Tooltip  transfer :content="scope.row.require" placement="top-start"  max-width='300'>
                                        <p style="width:200px;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;cursor: pointer;">
                                            {{scope.row.require}}
                                        </p>
                                    </Tooltip>
                                </template>

                            </el-table-column>
                            <el-table-column prop="duration" label="整改期限（天）"></el-table-column>
                            <el-table-column prop="enableFlag" label="状态">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.enableFlag == 1">
                                        <!-- <Icon type="md-checkmark-circle" style="color:#ccc;font-size: 18px;"/> -->
                                        <span class="green">已启用</span>
                                    </div>
                                    <div v-if="scope.row.enableFlag==0" >
                                        <!-- <img src="../../assets/images/quality/problem/disable.png" alt="" width="15" height="15" style="vertical-align: middle;"> -->
                                        <span class="red">已禁用</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center" width="150px" v-if="auth.isEdit||auth.isEnable||auth.isDelete">
                                <template slot-scope="scope">
                                    <el-button @click.native.prevent="updateRow(8,scope.row)" type="text" size="small" v-if="auth.isEdit">编辑</el-button>

                                    <el-button v-if="scope.row.enableFlag == 1&&auth.isEnable" style="color:red" @click.native.prevent="updateRow(7,scope.row)" type="text" size="small">禁用</el-button>

                                    <el-button v-if="scope.row.enableFlag == 0&&auth.isEnable" style="color:red" @click.native.prevent="updateRow(7,scope.row)" type="text" size="small">启用</el-button>
                                    <el-button style="color:red" @click.native.prevent="issueRemoveRow(scope.row)" type="text" size="small" v-if="auth.isDelete">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="clearfix pageFix" v-show="issueList.length>0">
                        <div class="float-right">
                            <Page v-if="totalCount" style="margin: 20px 0;text-align: right;" :current="current" :total="totalCount" :page-size="10" show-elevator show-total @on-change="pageChange"></Page>
                        </div>
                    </div>
                </div>

            </div>

        </div>

        <Modal class-name="msgModal" v-model="deleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(8)">取消</div>
                    <div class="button submit" @click="detele" v-preventReClick="1500">确定</div>
                </div >
            </div>
        </Modal>

        <Modal class-name="msgModal" v-model="issueDeleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(5)">取消</div>
                    <div class="button submit" @click="issueDetele" v-preventReClick="1500">确定</div>
                </div >
            </div>
        </Modal>

        <Modal class-name="msgModal" v-model="enableModal" title="状态编辑" width="360px;" :mask-closable="false">
            <div style="margin:10px" v-if="enable!=1">确定禁用这条数据吗？</div>
            <div style="margin:10px" v-else>确定启用这条数据吗？</div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(6)">取消</div>
                    <div class="button submit" @click="enableBtn" v-preventReClick="1500">确定</div>
                </div >
            </div>
        </Modal>

        <Modal class-name="msgModal" v-model="modal" :title="isAdd?'添加明细':'编辑明细'"  :mask-closable="false">
            <div>
                <div class="item2">
                    <i class="tip">*</i>
                    <span>整改期限:</span>
                    <Input v-model.number="timeLimit" :maxlength="3" placeholder="请输入整改期限" style="width: 330px" clearable/>
                    <i style="font-style:normal;margin-left:5px;" >天</i>

                </div>
                <div class="item2 myItem">
                    <i class="tip">*</i>
                    <span>检查内容:</span>
                    <Input v-model="content" type="textarea" :maxlength="50" style="width:350px" :autosize="{minRows: 2}" placeholder="请输入检查内容" clearable/>
                </div>
                <div class="item2 myItem">
                    <i class="tip">*</i>
                    <span>整改要求:</span>
                    <Input v-model="requirements" type="textarea" :maxlength="200" style="width:350px" :autosize="{minRows: 8}" placeholder="请输入整改要求" clearable/>
                </div>
            </div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(7)">取消</div>
                    <div class="button submit" @click="submitBtn(10)" v-preventReClick="1500">保存</div>
                </div >
            </div>
        </Modal>

        <Modal class-name="msgModal" v-model="classModal" title="添加类别" width="900px" :mask-closable="false" footer-hide>
            <div class="addClassModal">
                <div class="top" style="padding: 0 20px;box-sizing: border-box;margin-bottom: 15px;">
                    <div class="button submit" v-if="!isSonFlag" style="width: 100px;" @click="updateRow(4)">+  添加类别</div>
                </div>
                <div class="classAdd" v-show="isClassAdd">
                    <div class="left">
                        <div class="item">
                            <span class="tip" style="color:red">*</span>
                            <span style="width:120px;text-align:right;">编码 ：</span>
                            <el-input :maxlength="4" placeholder="请输入编码" style="width: 300px;"  v-model="classCode">
                                <template slot="prepend" v-if="isSonFlag&&parentCode!=null&&parentCode!=''">{{parentCode}}</template>
                            </el-input>
                        </div>
                        <div class="item" >
                            <span class="tip" style="color:red">*</span>
                            <span style="width:120px;text-align:right;">类别名称：</span>
                            <el-input :maxlength="20" placeholder="请输入类别名称" style="width: 300px;"  v-show="inputShow"   v-model="className"></el-input>
                            <el-input placeholder="请输入类别名称" style="opacity:0;position: absolute;top:-9999px;width:1px;"  v-show="inputShow"   ></el-input>
                            <div class="item" style="margin: 0">
                                <div class="button cancel" style="height: 40px;line-height: 40px;" @click="cancel(9)">取消</div>
                                <div class="button submit" style="height: 40px;line-height: 40px;" @click="submitAll" v-preventReClick="1500">确定</div>
                            </div>
                        </div>

                    </div>

                </div>
                <div class="tableBox">
                    <div class="tableList">
                        <el-table :data="treeData" height='500' border style="width: 100%" row-key="issueTypeId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                            <el-table-column label="编码" prop="code"> </el-table-column>
                            <el-table-column label="名称" prop="name"> </el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button style="color:#00ACFB;" @click.native.prevent="updateRow(10, scope.row)" type="text" size="small" v-preventReClick="1500">新建下级</el-button>
                                    <el-button style="color:#00ACFB;" @click.native.prevent="updateRow(9, scope.row)" type="text" size="small" v-preventReClick="1500">编辑</el-button>
                                    <el-button style="color:#FF001E;" @click.native.prevent="removeRow(scope.row)" type="text" size="small" >删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

            </div>
        </Modal>
    </div>
</template>

<script>
import { toTree, trans } from "@/sever/config.js";
import {
    getIssueTypeList,
    getIssueTypeAdd,
    getIssueTypeEdit,
    getIssueTypeDel,
    getIssueList,
    getIssueAdd,
    getIssueEdit,
    getIssueEnable,
    getIssueDel
} from '@/api/quality'
export default {
    data() {
        return {
            expandedKeys:[0],
            currentKey: '',
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            classAddFlag:false,
            detailAddFlag:false,
            enable:"",
            issueId:"",
            parentCode:"",
            isSonFlag:false,
            pid:"",
            classCode:'',
            className:'',
            keyword:"",
            inputShow:false,
            isClassAdd:false,
            classModal:false,
            requirements:"",
            content:"",
            timeLimit:"",
            totalCount: "",
            current: 1,
            pageNum: 1,
            pageSize: 10,
            modal: false,
            isAdd: true,
            deleteModal: false,
            enableModal:false,
            issueDeleteModal:false,
            treeData: [],
            issueList: [],
            list: [],
            projectId:"",
            classList: [],
            auth:{
                isAdd:false,
                isEdit:false,
                isEnable:false,
                isDelete:false,
                isType:false
            }, 
            btnList:[] //权限列表
        };
    },
    methods: {
        initAuth(){
            this.auth.isAdd = this.btnList.includes('quality/problem/add')
            this.auth.isEdit = this.btnList.includes('quality/problem/edit')
            this.auth.isEnable = this.btnList.includes('quality/problem/enable')
            this.auth.isDelete = this.btnList.includes('quality/problem/delete')
            this.auth.isType = this.btnList.includes('quality/problem/type')
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        getIssueAllList() {
            let params = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                issueTypeId: this.issueTypeId
            };
            getIssueList(params)
                .then(res => {
                    if (res.code == 200) {
                        this.issueList = res.data.list;
                        this.totalCount = res.data.total;

                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        pageChange(index) {
            this.pageNum = index;
            this.getIssueAllList();
        },
        getIssueTypeAll() {
            let parmas = {
                deptId:this.projectId,
                keyword:'',
            }
            getIssueTypeList(parmas).then(res => {
                if (res.code == 200) {
                    if(res.data.list.length > 0){
                        this.list = res.data.list;
                        this.treeData = trans(this.list);
                        this.issueTypeId = this.treeData[0].issueTypeId;
                        this.getIssueAllList();
                        this.$nextTick(()=>{
                            this.currentKey = this.issueTypeId
                            this.$refs['treeBox'].setCurrentKey(this.currentKey)
                        })
                    }else{
                        this.treeData = [];
                        this.issueTypeId = '';
                        this.currentKey = ""
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            })
            .catch(error => {
                console.log(error);
            });
        },
        getTreeId(index) {
            this.issueTypeId = index.issueTypeId;
            if(index.children){
                this.detailAddFlag=true;
            }else{
                this.detailAddFlag=false;
            }
            this.pageNum = 1
            this.getIssueAllList();
        },
        issueRemoveRow(row) {
            this.issueDeleteModal = true;
            this.issueId = row.issueId;
        },
        removeRow(row) {
            this.deleteModal = true;
            this.issueTypeId = row.issueTypeId;
        },
        enableBtn(){
            let params ={
                enable:this.enable,
                issueId:this.issueId,
            }
            getIssueEnable(params)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.enable='';
                        this.issueId='';
                        this.getIssueAllList();
                        this.enableModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
            })
        },
        detele() {
            getIssueTypeDel(this.issueTypeId)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getIssueTypeAll();
                        this.deleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
            });
        },
        issueDetele() {
            getIssueDel(this.issueId)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getIssueAllList();
                        this.issueDeleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
            });
        },
        cancel(type) {
            if(type==10){
                this.classModal=false;
                this.isSonFlag=false;
                this.isClassAdd=false;
                this.className='';
                this.classCode='';
                this.pid = '';
            }else if(type==9){
                this.isSonFlag=false;
                this.isClassAdd=false;
                this.className='';
                this.classCode='';
                this.pid = '';
            }else if(type==8){
                this.deleteModal=false;
                this.issueTypeId="";
            }else if(type==7){
                this.modal=false;
                this.content='';
                this.requirements='';
                this.timeLimit='';
            }else if(type==6){
                this.enableModal=false;
                this.enable =  '';
                this.issueId =  '';
            }else if(type==5){
                this.issueDeleteModal=false;
                this.issueId =  '';
            }
        },
        updateRow(type, row, rows) {
            if(type==10){
                this.pid = row.issueTypeId;
                this.parentCode = row.code;
                this.classCode='';
                this.className='';
                this.isSonFlag=true;
                this.isClassAdd=true;
                this.isAdd=true;

            }else if(type==9){
                this.pid = row.issueTypeId;
                let code =  row.code.split(".")
                let parentCode = '';
                for (let i = 0; i < code.length-1; i++) {
                    parentCode+=code[i]+',';
                }
                this.isSonFlag=true;
                this.isClassAdd=true;
                this.parentCode = parentCode;
                this.classCode =  code[code.length-1];
                this.className = row.name;
                this.isAdd=false;
            }else if(type==8){
                this.modal=true;
                this.content =  row.content;
                this.timeLimit =  row.duration;
                this.requirements =  row.require;
                this.issueId =  row.issueId;
                this.isAdd=false;
            }else if(type==7){
                this.enableModal=true;
                this.enable =  row.enableFlag==1?'0':'1';
                this.issueId =  row.issueId;
            }else if(type==6){
                this.modal = true;
                this.isAdd = true;
                this.content = "";
                this.timeLimit =  "";
                this.requirements =  "";
                this.issueId =  "";

            }else if(type==5){
                this.classModal = true;
                this.isClassAdd = false;
                this.classCode='';
                this.className='';
                this.isSonFlag=false;
                this.parentCode = "";
            }else if(type==4){
                this.isClassAdd = true;
                this.isSonFlag = true;
                this.isAdd = true;
                this.parentCode = "";
                this.pid = "";
            }

        },
        submitAll() {
            if(this.classCode===''){
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;
            }else{
                let reg =  /^[0-9]*$/;
                if(!reg.test(this.classCode)){
                    this.$Modal.warning({
                            title: "提示",
                            content: "编码格式错误"
                        });
                        return;
                }
            }

            if(this.className==''){
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;
            }
            if (this.isAdd) {
                let params = {
                    deptId: this.projectId,
                    pid: this.pid,
                    code: this.classCode,
                    name: this.className
                };
                getIssueTypeAdd(params)
                    .then(res => {
                        if (res.code == 200) {
                            this.success();
                            this.getIssueTypeAll();
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            } else {
                let params = {
                    issueTypeId: this.pid,
                    name: this.className,
                    code: this.classCode,
                };
                getIssueTypeEdit(params)
                    .then(res => {
                        if (res.code == 200) {
                            this.success();
                            this.getIssueTypeAll();
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            }
        },
        submitBtn(type){
            if(this.content==''||this.requirements==''||this.timeLimit==''){
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;

            }
            if( typeof this.timeLimit!= 'number'){
                this.$Modal.warning({
                    title: "提示",
                    content: "请输入正确的时间"
                });
                return;
            }
            if(this.isAdd){
                let params = {
                    issueTypeId:this.issueTypeId,
                    content:this.content,
                    require:this.requirements,
                    duration:Number(this.timeLimit)
                }
                getIssueAdd(params).then((res) => {
                    if (res.code == 200) {
                        this.modal=false;
                        this.content='';
                        this.requirements='';
                        this.timeLimit='';
                        this.success();
                        this.getIssueAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch((err) => {
                    console.log(err)
                });
            }else{
                let params = {
                    issueId:this.issueId,
                    content:this.content,
                    require:this.requirements,
                    duration:Number(this.timeLimit)
                }
                getIssueEdit(params).then((res) => {
                    if (res.code == 200) {
                        this.modal=false;
                        this.content='';
                        this.requirements='';
                        this.timeLimit='';
                        // this.deptId = this.deptpid;
                        this.success();
                        this.getIssueAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch((err) => {
                    console.log(err)
                });
            }
        },
        success() {
            this.$Message.success("操作成功");
            // this.classModal = false;
            this.isSonFlag=false;
            this.isClassAdd=false;
            this.classCode='';
            this.className='';
            this.pageNum = 1;
            this.isAdd=true;
        },
        getSearch(){
            this.getIssueTypeAll()
        },
        issueTypeTreeExpand(data) {
            data.forEach(obj => {
                if(obj.name.indexOf(this.keyword)!=-1){
                    this.expandedKeys.push(obj.issueTypeId)
                }
                if (obj.children instanceof Array) {
                    obj.children.forEach(v=>{
                        if(v.name.indexOf(this.keyword)!=-1){
                            this.expandedKeys.push(obj.issueTypeId)
                        }
                    })
                    this.issueTypeTreeExpand(obj.children)
                }
            })
            return data
        },
        renderContent(h, { node, data, store }) {
            return (
            <span class="custom-tree-node">
                <span title={node.label}>{node.label}</span>
            </span>);
        },
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        }
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.projectId = val.deptId;
                // this.deptName = val.name;
                this.pageNum = 1;
                this.current = 1;
                this.getIssueTypeAll();

            }
        },
        keyword(val){
            this.$refs.treeBox.filter(val);
        }
    },
    mounted() {
        this.projectId = this.$store.state.porjectObject.deptId;
        this.getIssueTypeAll();
        this.btnList = JSON.parse(localStorage.getItem("arr"));//localStorage当中的arr项存取的是按钮权限列表
        this.initAuth() //初始化权限
        // this.getIssueAllList();
        setTimeout(()=>{
            this.inputShow = true;
        },1)
    }
};
</script>

<style scoped lang="less">
@import "./../../assets/style/themeBase.less";
</style>

<style lang="scss" scoped>
@import "../../assets/style/qualityAndSafety/problem.scss";
@import "./../../assets/style/qualityAndSafety/modal.scss";
</style>
